package com.dindang.ddm.mvp.presenter;

import android.app.Application;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.dindang.ddm.app.AppConst;
import com.dindang.ddm.app.utils.APKVersionCodeUtils;
import com.dindang.ddm.app.utils.Base64Util;
import com.dindang.ddm.mvp.model.entity.BaseResponse;
import com.dindang.ddm.mvp.model.entity.VersionEntity;
import com.dindang.ddm.mvp.ui.activity.MainActivity;
import com.dindang.ddm.mvp.ui.widget.VersionTipDialog;
import com.jess.arms.integration.AppManager;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.http.imageloader.ImageLoader;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

import javax.inject.Inject;

import com.dindang.ddm.mvp.contract.AboutDingDangContract;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.LogUtils;
import com.jess.arms.utils.RxLifecycleUtils;
import com.longxi.gamer_base.BaseAppConst;
import com.longxi.gamer_base.dialog.WaitDialog;
import com.longxi.gamer_base.model.User;
import com.longxi.gamer_base.utils.SharedPreferencesUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 04/22/2019 15:35
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
@ActivityScope
public class AboutDingDangPresenter extends BasePresenter<AboutDingDangContract.Model, AboutDingDangContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;
    private WaitDialog mWaitDialog;
    private VersionEntity mData = new VersionEntity();
    private String path="/Downlaad/";
    Handler handler=new Handler();

    @Inject
    public AboutDingDangPresenter(AboutDingDangContract.Model model, AboutDingDangContract.View rootView) {
        super(model, rootView);
    }

    public void init() {
        mWaitDialog = new WaitDialog(mRootView.getActivity());
        //判断SD卡是否挂载
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            File externalStorageDirectory = Environment.getExternalStorageDirectory();
            String absolutePath = externalStorageDirectory.getAbsolutePath();
            path=absolutePath+path;
            ///storage/emulated/0/Downlaad/jinritoutiao.apk
            Log.i(TAG, "zp"+ path );
        }
        mRootView.getVersion().setText("当前版本:"+ APKVersionCodeUtils.getVerName(mRootView.getActivity()));
        getData();
    }

    /**
     * 获取版本信息接口
     */
    private void getData() {
        mWaitDialog.showWaitingDialog(ArmsUtils.getString(mApplication, com.dindang.checkline.R.string.data_load));
        VersionEntity.VersionPara mParam = new VersionEntity.VersionPara();
        mModel.getVersion(mParam)
                .subscribeOn(Schedulers.io())
                .retryWhen(new RetryWithDelay(0, 0))//遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
                .doOnSubscribe(disposable -> {

                }).subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(() -> {
                    mWaitDialog.hideWaitingDialog();
                })
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .subscribe(new ErrorHandleSubscriber<BaseResponse<VersionEntity>>(mErrorHandler) {
                    @Override
                    public void onNext(BaseResponse<VersionEntity> response) {
                        if(!response.isSuccess()){
                            ArmsUtils.makeText(mApplication, response.getStatuMsg());
                            return;
                        }
                        mData = response.getData();
                        if(mData.isHasNewVersion()){//有新版本
                            showDialog();
                        }
                    }
                });
    }

    VersionTipDialog.Builder mDialog;
    private void showDialog(){
        if(mDialog != null){
            mDialog.show();
        }else{
            mDialog = new VersionTipDialog.Builder(mRootView.getActivity());
            mDialog.setTip("发现新版本V"+mData.getUrl()+"，是否确定马上更新？")
                    .setProperty(new VersionTipDialog.OnPaymentListener() {
                        @Override
                        public void onClick() {//跳转下载页面
                            // http://www.wuxirui.com/download/jinritoutiao.apk
                            if(mData.getUrl().contains(".")){
                                String typeName = mData.getUrl().substring(mData.getUrl().lastIndexOf(".") + 1);
                                if(mData.getUrl().contains("/")){
                                    String filename = mData.getUrl().substring(mData.getUrl().lastIndexOf("/") + 1, mData.getUrl().lastIndexOf("."));
                                    path = path + filename + "." + typeName;
                                }
                            }

                            Log.e(TAG, "路径"+path);
                            //下载
                            try {
                                download(mData.getUrl(), new File(path), new DownLoadListener() {
                                    @Override
                                    public void Success(String path) {
                                        Log.e(TAG, "success: " + path);
                                        //自动安装APK
                                        installApk(new File(path));
                                    }

                                    @Override
                                    public void Failed(Exception e) {
                                        Log.e(TAG, "failed: " + e.getMessage());

                                    }

                                    @Override
                                    public void Progress(final long progress) {
                                        Log.i(TAG, "progress: " + progress);
                                        handler.post(new Runnable() {
                                            @Override
                                            public void run() {
    //                                            tv.setText(progress+"%");
                                            }
                                        });
                                    }
                                });
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    })
                    .create()
                    .show();
        }
    }

    public void download(String url, final File file, final DownLoadListener listener) throws IOException {
        ///storage/emulated/0/Downlaad/jinritoutiao.apk
        //判断发目录是否存在
        File parentFile = file.getParentFile();
        if(!parentFile.exists()){
            parentFile.mkdir();
        }
        //判断文件是否存在
        if(!file.exists()){
            file.createNewFile();
        }

        Request request = new Request.Builder()
                .get()
                .url(url)
                .build();
        OkHttpClient client = new OkHttpClient();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        listener.Failed(e);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                ResponseBody body = response.body();

                long l = body.contentLength();

                FileOutputStream fos = new FileOutputStream(file);
                InputStream is = body.byteStream();

                byte[] bytes = new byte[2048];
                int len=0;
                int sum=0;
                while ((len=is.read(bytes,0,bytes.length)) != -1){
                    sum+=len;
                    long progress=sum*100/l;
                    listener.Progress(progress);
                    fos.write(bytes,0,len);
                }
                fos.flush();
                is.close();
                fos.close();

                listener.Success(file.getAbsolutePath());

            }
        });
    }

    /**
     * 安装apk
     * @param file
     */
    private void installApk(File file) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        mRootView.getActivity().startActivity(intent);
        android.os.Process.killProcess(android.os.Process.myPid());
    }


    /**
     *   1.请求成功  2.请求失败  3.下载进度条
     */

    public interface DownLoadListener {
        void Success(String path);

        void Failed(Exception e);

        void Progress(long progress);
    }

    public interface NewCallBack {
        void onSuccess(Object o);
        void onFailed(Exception e);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }
}
